<template>
<!-- Main content -->
<div>
    <div class="row">
        <div class="col-xs-12">
            <theme-box title="权重列表">
                <table class="table table-bordered table-striped" style="width:100%" v-el:table></table>
            </theme-box>
        </div>
        <!-- /.col -->
    </div>
    <modal-container title="编辑" v-el:modal v-ref:modal class="edit-modal" theme="small_window">
        <form @submit.prevent @reset.prevent v-el:mform>
            <div class="modal-body">
                <table-modal :item="item" :columns-set="columnsSet" :columns-num="1"></table-modal>
            </div>

            <div class="modal-footer">
                <v-button data-dismiss="modal" @click="resetBindDrag">关闭</v-button>
                <v-button theme="primary" type="submit">保存</v-button>
            </div>
        </form>

    </modal-container>

    <modal-container title="试算" v-el:trial-modal v-ref:trial-modal class="edit-modal" theme="big">
        <form @submit.prevent @reset.prevent v-el:Trial-form>
            <div class="modal-body">
                <table-modal :item="item" :columns-set="columnsTrialSet" :columns-num="2" v-ref:item></table-modal>
            </div>

            <div class="modal-footer">
                <v-button data-dismiss="modal" @click="resetBindDrag">关闭</v-button>
                <v-button theme="primary" type="submit">保存</v-button>
            </div>
        </form>

    </modal-container>
    <!-- /.row -->
</div>
<!-- /.content -->
</template>

<style lang="less" scoped>
.form-inline .btn+.btn {
    margin-right: 10px;
}
.form-inline .form-group+.form-group {
    margin-left: 20px;
}

</style>
<script>
import {
    columnsSet,
    columnsTrialSet
} from './columns.js'
import {
    dateTime
} from 'ui/collections/general.js'
var serialize = require('form-serialize');

var dataTable;
export default {
    data: () => ({
        item: {},
        columnsSet: [],
        stateOptions: [{
            key: "所有状态",
            value: ""
        }, {
            key: "开启",
            value: "0"
        }, {
            key: "关闭",
            value: "1"
        }],
        columnsTrialSet: columnsTrialSet
    }),
    methods: {
        //还原弹出框位置
        resetBindDrag() {
            this.$refs.modal._resetBindDrag();
            this.$refs.trialModal._resetBindDrag();
        },
        //查询按钮
        search: function() {
            dataTable.ajax.reload();
        },
        //重置按钮
        reset: function() {
            $(".form-inline")[0].reset();
            dataTable.ajax.reload();
        }
    },
    ready: async function() {
        var typeWatch = function(){};
        this.$set("columnsSet", columnsSet)
        var self = this;
        //创建dataTable
        dataTable = $(this.$els.table).DataTable({
            "columns": this.columnsSet, //定义列
            "ajax": async function(data, callback, settings) {
                var page = [{
                    "name": "iDisplayStart",
                    "value": 1 + data.start / data.length
                }, {
                    "name": "iDisplayLength",
                    "value": data.length
                }];
                var _data = {};
                _data.aoData = JSON.stringify(page);
                //发送请求
                var result = await self.$post({
                    url: "/api/v1" + projectName_Url + "/plat/weight/query",
                    method: "GET"
                })
                if (result.respCode != "00") {
                    Midway.alert({
                        title: "操作失败",
                        content: result.content
                    })
                }
                callback({
                    recordsTotal: result.content.total,
                    recordsFiltered: result.content.total,
                    data: result.content.info || []
                })
            }
        });

        $(self.$el).on("click", ".edit", function() {
            var Row = $(this).closest('tr').get(0);
            const dataArray = JSON.parse(JSON.stringify(dataTable.row(Row).data()));
            self.item = dataArray;
            setTimeout(()=>{
                //时间选择设置
                dateTime({
                    format: "yyyy-mm-dd",
                    minView: "2"
                })
            },600)
            //编辑框验证、保存、提交
            $(self.$els.mform).validate(self.item.valdate = {
                async submitHandler(form) {
                    var _data = serialize(form, {
                        hash: true,
                        disabled: true,
                        empty: true
                    });
                    //数据处理
                    let myData = {};
                    let total = 0;
                    for (var key in _data) {
                        if (_data.hasOwnProperty(key)) {
                            myData[key] = +_data[key]
                        }
                        if (key != "id" && myData.hasOwnProperty(key)) {
                            total = total + myData[key] * 100;
                        }
                    }
                    if (total != 100) {
                        Midway.alert({
                            title: "温馨提示",
                            content: "合计必须为1"
                        })
                        return
                    }
                    myData.updOpr = JSON.parse(localStorage.getItem("get_id"));
                    await self.$post({
                        url: "/api/v1/" + projectName_Url + "plat/weight/1",
                        data: myData,
                        method: "PUT"
                    });
                    dataTable.ajax.reload(null, false);
                    $(self.$els.modal).modal('hide');
                    self.resetBindDrag()
                },
                rules: {
                    id: {
                        required: true
                    },
                    effDate: {
                        required: true,
                        number: true,
                        max: 0.5,
                        min:0
                    },
                    evValue: {
                        required: true,
                        number: true,
                        max: 0.5,
                        min:0
                    },
                    unavDate: {
                        required: true,
                        number: true,
                        max: 0.5,
                        min:0
                    },
                    usageCou: {
                        required: true,
                        number: true,
                        max: 0.5,
                        min:0
                    },
                    usageScope: {
                        required: true,
                        number: true,
                        max: 0.5,
                        min:0
                    },
                    useTimePeriod: {
                        required: true,
                        number: true,
                        max: 0.5,
                        min:0
                    },
                    usageRules: {
                        required: true,
                        number: true,
                        max: 0.5,
                        min:0
                    }

                },
                messages: {

                }
            });
            $(self.$els.modal).modal('show');
        });


        $(self.$el).on("click", ".trial", async function() {
            //时间选择设置
            self.$nextTick(()=>{
                dateTime({
                    format: "yyyy-mm-dd",
                    minView: "2"
                })
            })

            self.item = {
                disableDate:[],
                useRule:[],
            };
            //抵用券的时候  抵用券限制金额显示
            typeWatch()
            typeWatch = self.$refs.item.$watch("item.type", function (v) {
                self.$nextTick(()=>{
                    dateTime({
                        format: "yyyy-mm-dd",
                        minView: "2"
                    })
                })
                if(v == 'voucher'){
                    self.columnsTrialSet.find(data => data.data == "restricted").edit = true;
                }else{
                    self.columnsTrialSet.find(data => data.data == "restricted").edit = false;
                }
            });
            $(self.$els.trialForm).validate(self.item.valdate = {
                async submitHandler(form) {
                    var _data = serialize(form, {
                        hash: true,
                        disabled: true,
                        empty: true
                    });
                    //进行不可使用日期的数据处理
                    var disableDate = [];
                    for (var key in _data.disableDate) {
                        if (_data.disableDate[key]) {
                            disableDate.push(_data.disableDate[key]);
                        }
                    }
                    delete _data.disableDate;
                    _data.disableDate = disableDate.join(",");
                    _data.begin = _data.begin.replace(/-/g, "");
                    _data.end = _data.end.replace(/-/g, "");
                    _data.useTime = "";
                    //useTime进行数据处理
                    for (var i = _data.useStartTime; i <= _data.useEndTime; i++) {
                        if (i == "24") {
                            i == _data.useTime || i == _data.useEndTime ? _data.useTime += 0 : _data.useTime += 0 + ","
                        } else {
                            i == _data.useTime || i == _data.useEndTime ? _data.useTime += i : _data.useTime += i + ","
                        }
                    }
                    //使用规则权重 数据处理
                    var useRule = [];
                    for (var key in _data.useRule) {
                        if (_data.useRule[key]) {
                            useRule.push(_data.useRule[key]);
                        }
                    }
                    delete _data.useRule;
                    _data.useRule = useRule.join("");

                    // return false
                    var result = await self.$post({
                        url: "/api/v1/" + projectName_Url + "plat/weight/1",
                        data: _data
                    });
                    Midway.alert({
                            title: "试算结果",
                            content: "芸币估值:" + result.content
                        })
                        // dataTable.ajax.reload(null, false);
                    $(self.$els.trialModal).modal('hide');
                    self.resetBindDrag()
                },
                errorPlacement: function(error, element) {
                    if (element.attr("name") == "disableDate" || element.attr("name") == "useRule") {
                        error.insertAfter(element.parents("div.checkbox-item"));
                    } else {
                        error.insertAfter(element)
                    }
                },
                rules: {
                    type: {
                        required: true
                    },
                    dbt: {
                        required: true
                    },
                    begin: {
                        required: true,
                        compareDate: ["begin", "end"]
                    },
                    end: {
                        required: true,
                        compareDate: ["begin", "end"]
                    },
                    useRule: {
                        required: true
                    },
                    useStartTime: {
                        required: true,
                        comparisonSize: ["useStartTime", "useEndTime"]
                    },
                    useEndTime: {
                        required: true,
                        comparisonSize: ["useStartTime", "useEndTime"]
                    },
                    usageCou: {
                        required: true
                    },
                    worth: {
                        required: true
                    },
                    denomination: {
                        required: true,
                        digits: true
                    },
                    dishNum: {
                        required: true,
                        digits: true
                    },
                    unDishType: {
                        required: true,
                        digits: true
                    },
                    num: {
                        required: true,
                        decNum:true
                    },
                    per: {
                        required: true,
                        digits: true
                    },
                    restricted: {
                        required: true,
                        digits: true
                    },
                    usageCou: {
                        required: true,
                    },
                    worth: {
                        required: true,
                        digits: true
                    }
                },
                messages: {

                }
            });
            $(self.$els.trialModal).modal('show');
        });
    },
    beforeDestroy() {
        $(this.$el).off("click")
    }
}
